﻿using System.ComponentModel;
using System.Reflection;

namespace Dyao.Book.Core
{
    public static class ReflectionHelper
    {
        /// <summary>
        /// Gets the member's underlying type.
        /// </summary>
        /// <param name="member">The member.</param>
        /// <returns>The underlying type of the member.</returns>
        public static Type GetMemberUnderlyingType(MemberInfo member)
        {

            switch (member.MemberType)
            {
                case MemberTypes.Field:
                    return ((FieldInfo)member).FieldType;
                case MemberTypes.Property:
                    return ((PropertyInfo)member).PropertyType;
                case MemberTypes.Event:
                    return ((EventInfo)member).EventHandlerType;
                case MemberTypes.Method:
                    return ((MethodInfo)member).ReturnType;
                default:
                    throw new ArgumentException("MemberInfo must be of type FieldInfo, PropertyInfo, EventInfo or MethodInfo", nameof(member));
            }
        }

        /// <summary>
        /// 获取实体导出列
        /// </summary>
        /// <param name="assemblyName">程序集名称</param>
        /// <param name="exportModelName">导出实体名称</param>
        /// <returns></returns>
        public static Dictionary<string, string> GetEntityExportColumn(string assemblyName, string exportModelName)
        {
            Type entityType = Assembly.Load(assemblyName).GetType(exportModelName, false, true);
            return GetEntityExportColumn(entityType);
        }

        /// <summary>
        /// 获取实体导出列
        /// </summary>
        /// <param name="type">导出实体类型</param>
        /// <returns></returns>
        public static Dictionary<string, string> GetEntityExportColumn(Type type)
        {
            PropertyInfo[] properties = type.GetProperties();
            Dictionary<string, string> propertys = new Dictionary<string, string>();
            foreach (PropertyInfo property in properties)
            {
                var attribute = property.GetCustomAttribute<DescriptionAttribute>();
                if (attribute != null)
                {
                    propertys.Add(property.Name, attribute.Description);
                }
            }
            return propertys;
        }
    }
}
